﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;

using SPaDevToolkit.Administration;
using SPaDevToolkit.Diagnostics;

using Northwind.Common.Diagnostics;

namespace Northwind.ServiceObjects
{
    [Guid("A7C9C974-950B-468C-BAA0-E154F5BDB292")]
    public sealed class NorthwindDatabase : SPaWebServiceApplicationDatabase
    {
        public static string ProvisioningScriptPath = @"Template\SQL\Northwind\NorthwindProvision.sql";

        #region Constructors
        public NorthwindDatabase() { }

        public NorthwindDatabase(SPDatabaseParameters northwindDatabaseParameters)
            : base(northwindDatabaseParameters)
        {
        }

        public NorthwindDatabase(string name, SPDatabaseServiceInstance serviceInstance)
            : base(name, serviceInstance) { }
        #endregion

        #region Overrides
        public override void Provision()
        {
            Logger.WriteTrace(string.Format("Provisioning service application database '{0}'", Name), 0, TraceSeverity.High, AreaNames.Northwind, CategoryNames.Service);
            try
            {
                base.Status = SPObjectStatus.Provisioning;
                this.Update();

                //TODO: Need checks on database. SqlDatabaseManager is an internal class in Microsoft.Office.Server.dll

                //SqlDatabaseManager manager = SqlDatabaseManager.FromConnectionString(base.DatabaseConnectionString);
                //if (!manager.Exists || manager.IsEmpty)
                //{
                Logger.WriteTrace(string.Format("Starting schema provisioning of Northwind database '{0}'", base.Name), 0, TraceSeverity.High, AreaNames.Northwind, CategoryNames.Service);
                Dictionary<string, bool> options = new Dictionary<string, bool>(3); //Copied from UPS databases. Indexes from SPDatabase
                options.Add(SPDatabase.SqlDatabaseOption[(int)DatabaseOptions.AutoClose], false);    //autoclose
                options.Add(SPDatabase.SqlDatabaseOption[(int)DatabaseOptions.ArithAbort], true);     //arithabort
                options.Add(SPDatabase.SqlDatabaseOption[(int)DatabaseOptions.TruncLogOnChkpt], true);  //trunc. log on chkpt.
                SPDatabase.Provision(base.DatabaseConnectionString, SPUtility.GetGenericSetupPath(ProvisioningScriptPath), options);
                this.NeedsUpgrade = false;
                this.GrantOwnerAccessToDatabaseAccount();
                //ULS.SendTraceTag(0x38316a39, ULSCat.msoulscat_SPS_UserProfiles, ULSTraceLevel.High, "Finished schema provisioning of ProfileDatabase '{0}'", new object[] { base.Name });
                Logger.WriteTrace(string.Format("Finished schema provisioning of Northwind database '{0}'", base.Name), 0, TraceSeverity.High, AreaNames.Northwind, CategoryNames.Service);
                //}
                //else
                //{
                //    ULS.SendTraceTag(0x38316a61, ULSCat.msoulscat_SPS_UserProfiles, ULSTraceLevel.High, "Starting schema evaluation of existing ProfileDatabase '{0}'", new object[] { base.Name });
                //    if (!manager.ExistsTable("PersonalSite"))
                //    {
                //        throw new SPDatabaseException(StringResourceManager.GetString("InvalidProfileDatabase"));
                //    }
                //    this.NeedsUpgrade = true;
                //    ULS.SendTraceTag(0x38316a62, ULSCat.msoulscat_SPS_UserProfiles, ULSTraceLevel.High, "Finished schema evaluation of existing ProfileDatabase '{0}'", new object[] { base.Name });
                //    if (!SPManager.PeekIsUpgradeRunning())
                //    {
                //        SPManager.Instance.RunUpgradeSession(this, false);
                //    }
                //    else
                //    {
                //        this.Upgrade();
                //    }
                //    this.AudienceRulesNeedUpgrade = true;
                //}
                base.Status = SPObjectStatus.Online;
                this.Update();
                    Logger.WriteTrace(string.Format("Finished Provisioning service application database '{0}'", Name), 0, TraceSeverity.High, AreaNames.Northwind, CategoryNames.Service);
            }
            catch (Exception ex)
            {
                Logger.WriteException(ex, "Error deleting Northwind Application Database", 0, EventSeverity.Error, AreaNames.Northwind, CategoryNames.Service);
                throw;
            }

        }


        #endregion
    }
}
